﻿using IceZero.Business.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IceZero.Web.Helpers
{
    public static class ActionHelper
    {
        /// <summary>
        /// 执行动作
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static IActionResult ExecAction(ControllerBase controller, Action<ControllerBase> action)
        {
            try
            {
                action(controller);
                return controller.Ok();
            }
            catch (IceZeroBusinessException ex)
            {
                return controller.BadRequest(ex.GetResult());
            }
            catch (IceZeroArgumentException ex)
            {
                return controller.BadRequest(ex.GetResult());
            }
            catch (Exception ex)
            {
                return controller.BadRequest(new IceZeroExceptionResult()
                {
                    Code = ExceptionCode.CError,
                    Message = ex.Message,
                    ExceptionSource = $"{ex.TargetSite.DeclaringType.FullName}.{ex.TargetSite.Name}",
                    StackTrace = ex.StackTrace
                });
            }
        }

        /// <summary>
        /// 执行动作
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static IActionResult ExecAction(ControllerBase controller, Func<ControllerBase, object> action)
        {
            try
            {
                return controller.Ok(action(controller));
            }
            catch (IceZeroBusinessException ex)
            {
                return controller.BadRequest(ex.GetResult());
            }
            catch (IceZeroArgumentException ex)
            {
                return controller.BadRequest(ex.GetResult());
            }
            catch (Exception ex)
            {
                return controller.BadRequest(new IceZeroExceptionResult()
                {
                    Code = ExceptionCode.CError,
                    Message = ex.Message,
                    ExceptionSource = $"{ex.TargetSite.DeclaringType.FullName}.{ex.TargetSite.Name}",
                    StackTrace = ex.StackTrace
                });
            }
        }
    }
}
